package com.yutianran.ezadapter.lv;

import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.yutianran.ezadapter.CommonViewHolder;
import com.yutianran.ezadapter.LayoutPlayer;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LvAdapter extends BaseAdapter {

    private final LvHelper helper;
    private List<?> data;
    private Map<Integer, Integer> viewType2layoutId = new HashMap<>();//viewType --> layoutId
    private Map<Integer, Integer> layoutId2viewType = new HashMap<>();//layoutId --> viewType

    public LvAdapter(LvHelper helper) {
        this.helper = helper;
    }

    public LvAdapter(LvHelper helper, List<?> data) {
        this.helper = helper;
        this.data = data;
    }

    public void initLayoutIdMap() {
        for (int i = 0; i < helper.getLayoutIds().size(); i++) {
            viewType2layoutId.put(i, helper.getLayoutIds().get(i));
            layoutId2viewType.put(helper.getLayoutIds().get(i), i);
        }
    }

    @Override
    public int getCount() {
        return data != null ? data.size() : 0;
    }

    @Override
    public Object getItem(int position) {
        return data != null ? data.get(position) : null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemViewType(int position) {
        Object item = data.get(position);
        Class<?> clazz = item.getClass();
        Map<Class, Integer> layoutIdMap = helper.getLayoutIdMap();
        Integer layoutId = layoutIdMap.get(clazz);
        Integer viewType = layoutId2viewType.get(layoutId);
        return viewType;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        int viewType = getItemViewType(position);
        int layoutId = viewType2layoutId.get(viewType);
        CommonViewHolder viewHolder = CommonViewHolder.get(convertView, parent, layoutId);
        LayoutPlayer<?> player = helper.getPlayerMap().get(layoutId);
        convert(player, position, viewHolder);
        return viewHolder.getItemView();
    }

    public void setData(List<?> data) {
        this.data = data;
        notifyDataSetChanged();
    }

    private <T> void convert(LayoutPlayer<T> player, int position, CommonViewHolder viewHolder) {
        T t = (T) getItem(position);
        player.bindData(t, viewHolder);
    }
}
